<?php

include_once 'getAccessToken.php';

function transId($dizhi) {
    $type = 'image';

    $filepath = dirname(__FILE__) . xiazai($dizhi);
    //echo $filepath;
    $data = array("media" => new \CURLFile($filepath));
    //$token = "vRxZYl7_MkblKXiyNvnilRBmjrUHh-2c0PXseAWv-1Mf9NEiXW4jzvyBy5TVb_vfKHCqF_i8gyReS63N8-Dz5IMue1hyBnGw7JOBbiCebLgDb7b1hYIP_yAX3MCYW3K1ABAgAHATUT";
    $token = GetAccessToken();
    $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$token&type=$type";
    //var_dump(shangchuan($data,$url));
    $jieguo = shangchuan($data, $url);
    //print_r($jieguo);
    $json_h = json_decode($jieguo, true);
    $id = $json_h['media_id'];
    return $id;
}

function shangchuan($data, $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}

function dlfile($file_url, $save_to) {
    $content = file_get_contents($file_url);
    file_put_contents($save_to, $content);
}

function download($url, $filename) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    //$filename = pathinfo($url, PATHINFO_BASENAME);

    $resource = fopen($filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
}

function xiazai($dizhi) {
    $time = time();
    $file = 'img\img_' . $time . '.jpg';
    download($dizhi, $file);
    return '\img\img_' . $time . '.jpg';
}